package org.example.mppg.util;

import cn.hutool.core.lang.Snowflake;
import org.apache.commons.lang3.StringUtils;

import java.net.InetAddress;
import java.util.concurrent.ThreadLocalRandom;

public class IdUtil {

    private static volatile Snowflake snowflake;

    private static volatile String nodeId;

    private static final int MAX_WORKER_ID = 31; // 最大 workerId

    private IdUtil() {
    }

    public static Snowflake getSnowflake() {
        if (snowflake == null) {
            synchronized (IdUtil.class) {
                if (snowflake == null) {
                    try {
                        InetAddress address = InetAddress.getLocalHost();
                        String paddedIp = ipToPaddedString(address.getHostAddress());
                        long workerId = Long.parseLong(paddedIp);
                        // 确保 workerId 在有效范围内
                        if (workerId > MAX_WORKER_ID) {
                            workerId = workerId % (MAX_WORKER_ID + 1);
                        }

                        snowflake = new Snowflake(workerId, ThreadLocalRandom.current().nextInt(0, 32));
                    } catch (Exception e) {
                        throw new IllegalArgumentException("linlong message middle create id generator error" + e.getMessage());
                    }
                }
            }
        }
        return snowflake;
    }

    public static String getNodeId() {
        if (StringUtils.isBlank(nodeId)) {
            synchronized (IdUtil.class) {
                if (StringUtils.isBlank(nodeId)) {
                    Snowflake snowflake = getSnowflake();
                    nodeId = snowflake.nextIdStr();
                }
            }
        }

        return nodeId;
    }

    private static String ipToPaddedString(String ipAddress) {
        StringBuilder stringBuilder = new StringBuilder();
        String[] parts = ipAddress.split("\\.");
        for (int i = 0; i < parts.length; i++) {
            String part = parts[i];
            int value = Integer.parseInt(part);

            // 格式化为三位，不足的部分补零
            if (i == 0) {
                // 第一个部分不补零
                stringBuilder.append(value);
            } else {
                // 不足三位时补零
                String formattedPart = String.format("%03d", value);
                stringBuilder.append(formattedPart);
            }
        }
        return stringBuilder.toString();
    }
}
